<template>
	<div>
		<canvas id="myCanvas" canvas-id="myCanvas" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
		<div class="flex action">
			<u-button class="flex-1" type="error" text="清除" @click="clearCanvas"></u-button>
			<u-button class="flex-1" type="primary" text="保存" @click="saveCanvas"></u-button>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				context: null,
				isDrawing: false,
				lastX: 0,
				lastY: 0,
				systemInfo: null
			}
		},
		onReady() {
			this.context = uni.createCanvasContext('myCanvas', this);
			this.systemInfo = uni.getSystemInfoSync()
		},
		methods: {
			touchStart(e) {
				this.isDrawing = true;
				this.lastX = e.touches[0].x;
				this.lastY = e.touches[0].y;
			},
			touchMove(e) {
				if (!this.isDrawing) return;

				let context = this.context;
				let lastX = this.lastX;
				let lastY = this.lastY;
				let currentX = e.touches[0].x;
				let currentY = e.touches[0].y;

				context.setStrokeStyle('#000000');
				context.setLineWidth(2);
				context.beginPath();
				context.moveTo(lastX, lastY);
				context.lineTo(currentX, currentY);
				context.stroke();

				this.lastX = currentX;
				this.lastY = currentY;
				context.draw(true);
			},
			touchEnd() {
				this.isDrawing = false;
			},
			clearCanvas() {
				this.context.clearRect(0, 0, this.systemInfo.screenWidth, this.systemInfo.screenHeight);
				this.context.draw(true);
			},
			saveCanvas() {
				uni.canvasToTempFilePath({
					canvasId: 'myCanvas',
					success: (res) => {
						// 将签名图片上传到服务器
						uni.uploadFile({
							url: 'http://your-server-url.com/upload',
							filePath: res.tempFilePath,
							name: 'file',
							success: (uploadRes) => {
								console.log(uploadRes.data);
							},
							fail: (error) => {
								console.log(error);
							}
						});
					}
				}, this);
			}
		}
	}
</script>

<style>
	canvas {
		width: 100vw;
		height: calc(100vh - 60px);
	}
	.flex {
		display: flex;
		align-items: center;
		gap: 30upx;
	}
	.flex-1 {
		flex: 1;
	}
	.action {
		padding: 0 10upx;
	}
</style>